package com.yuzai.reading.services.impl;

import cn.hutool.core.util.ObjectUtil;

import com.yuzai.reading.dtos.UserDTO;
import com.yuzai.reading.entitys.UserEntity;
import com.yuzai.reading.mappers.UserMapper;
import com.yuzai.reading.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * @param userDTO
     * @return
     */
    @Override
    public boolean queryUser(UserDTO userDTO) {
        //数据库中查询
        UserEntity userEntity = userMapper.selectUserById(userDTO.getUsername());
        if (ObjectUtil.isNull(userEntity)) {
            //为空
            return false;
        }
        //判断密码
        if (userEntity.getPassword().equals(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()))) {
            //正确
            return true;
        }

        return false;
    }

    @Override
    public void updateUserToken(UserDTO userDTO, String token) {
        //修改token
        userMapper.updateUser(userDTO.getUsername(), token);
    }

    @Override
    public UserEntity register(UserDTO userDTO) {
        //查询数据库是否存在
        UserEntity userEntity = userMapper.selectUserById(userDTO.getUsername());
        if (ObjectUtil.isNotNull(userEntity)) {
            //账号存在
            return null;
        }
        UserEntity user = new UserEntity();
        user.setUsername(userDTO.getUsername())
                .setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()))
                .setExpire(System.currentTimeMillis() / 1000)
                .setCreate_time(LocalDateTime.now());
        userMapper.insertUser(user);
        return user;
    }

    @Override
    public boolean checkSecret(String secret) {

        //查询cdk是否已经被使用

        //查询出卡密的vip时间

        //修改指定username对应的expire时间

        return false;
    }

}
